package sy.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.ui.Model;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import sy.model.SysAccount;
import sy.service.PerAddressServiceI;
import sy.service.SysAccountServiceI;
import sy.service.SysFunctionServiceI;

import sy.util.Menu;
import sy.util.MessageObject;

@Controller
@SessionAttributes("currAccount")
@RequestMapping("indexController")
public class IndexController {
	
	private SysAccountServiceI sysAccountService;
	private SysFunctionServiceI sysFunctionService;
	
	public SysAccountServiceI getSysAccountService() {
		return sysAccountService;
	}

	@Autowired
	public void setSysAccountService(SysAccountServiceI sysAccountService) {
		this.sysAccountService = sysAccountService;
	}
	
	public SysFunctionServiceI getSysFunctionService() {
		return sysFunctionService;
	}

	@Autowired
	public void setSysFunctionService(SysFunctionServiceI sysFunctionService) {
		this.sysFunctionService = sysFunctionService;
	}
	
	
	/************************** view controller ***************************/


	/**
	 * @Description: 首页
	 * @param 
	 * @author     :wjy
	 * Create Date : 2017年7月25日 
	 */
	@RequestMapping("/index")
	public String index(Model model){
		return "index";
	}
	
	/**
	 * @Description: 注册页
	 * @param 
	 * @author     :wjy
	 * Create Date : 2017年7月25日 
	 */
	@RequestMapping("/register")
	public String register(){
		return "register";
	}
	
	/**
	 * @Description: 登录页
	 * @param 
	 * @author     :wjy
	 * Create Date : 2017年7月25日 
	 */
	@RequestMapping("/login")
	public String login(){
		return "login";
	}
	
	/**
	 * @Description: 退出系统
	 * @param 
	 * @author     :wjy
	 * Create Date : 2017年7月25日 
	 */
	@RequestMapping(value="/index",params="logout",method=RequestMethod.GET)
	public String logout(SessionStatus sessionStatus) {
		sessionStatus.setComplete();
		return "redirect:/indexController/login";
	}
	
	/************************** data controller ***************************/
	
	/**
	 * @Description: 登录
	 * @param 
	 * @author     :wjy
	 * Create Date : 2017年7月25日 
	 */
	@RequestMapping(value="/process/login", method = RequestMethod.POST)
	public String login(HttpServletRequest request, Model model) {
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		SysAccount account = (SysAccount)sysAccountService.login(name, password);
		if(account==null){
			return "redirect:/indexController/login?error=1";
		}
			model.addAttribute("currAccount", account);
			return "redirect:/indexController/index";

	}	
	/**
	 * 
	 * @Title      : getMenu 
	 * @Description: TODO
	 * @param request
	 * @param model
	 * @return     : Map<String,List<Menu>>
	 * @author     :xieyuanqiu
	 * Create Date : 2017年7月31日 上午10:32:32
	 * @throws
	 */
	@RequestMapping(value="/process/getMenu", method = RequestMethod.POST)
	@ResponseBody
	public Map<String,List<Menu>> getMenu(@ModelAttribute("currAccount")SysAccount currentUser, SessionStatus sessionStatus ){
		Map<String,List<Menu>> menuMap = new HashMap<String,List<Menu>>();
		String user = currentUser.getName();
		/**
		 * 判断用户是否已登陆，没登录则注销session
		 */
		if ("".equals(user) || null == user){
			sessionStatus.setComplete();
			return null;
		}
		/**
		 * 获取所有父节点（pid=null）
		 */
		List<Menu> parentlist = sysFunctionService.listMenuByType(user, "parent", "");
		List<Menu> parentlistNew = new ArrayList<Menu>();
		menuMap.put("parent", parentlist);
		StringBuffer sb = new StringBuffer();
		/**
		 * 存放叶子节点
		 */
		List<Menu> children = new ArrayList<Menu>();
		/**
		 * 获取id!=null的父节点（上一步获取父节点时返回有一行空数据，此处将它排除）
		 */
		for(Menu menu : parentlist){
			if (menu.getId() != null && menu.getId() != "null") {
				sb.append(menu.getId()+",");
			}
		}
		if (sb.toString().indexOf(",")>0) {
			/**
			 * 根据得到的父节点获取所有其子节点
			 */
			children = sysFunctionService.listMenuByType(user, "", sb.toString().substring(0, sb.toString().length()-1));
			menuMap.put("children", children);
		} 
		/**
		 * 此标识用来区分某个父节点下是否有子节点，没有则不返回该父节点
		 */
		boolean flag = false;
		/**
		 * 将子节点归属到所属父节点下
		 */
		for(Menu menuParent : parentlist){
			if (menuParent.getId() != null && menuParent.getId() != "null") {
				for(Menu menuChildren : children){
					if (menuParent.getId().equals(menuChildren.getPid())) {
						flag = true;
						break;
					}
				}
			}
			/**
			 * 如果有子节点，添加到返回数据队列中
			 */
			if (flag) {
				parentlistNew.add(menuParent);
				flag = false;
			} else {}
		}
		menuMap.put("parent", parentlistNew);
		return menuMap;
	}
}
